<template>
  <div class="asnBill">
    <el-dialog
      title="转移SO到新的波次"
      :visible.sync="dialogTransVisible"
      :before-close="handleClose"
      width="500px"
      style="margin-top: -10vh"
    >
      <el-table
        highlight-current-row
        @current-change="handleSelChange"
        :data="WaveMasters"
        style="width: 100%"
      >
        <el-table-column fixed="left" type="index" width="55">
        </el-table-column>
        <el-table-column sortable prop="waveId" label="波次编码">
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="150">
          <template slot-scope="scope">
            <el-button
              @click="transToWaveConfirm(scope.row.waveId)"
              type="edit"
              plain
              size="small"
              >转移至此波次
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog
      title="分配仓管员"
      :visible.sync="dialogAllocate"
      :before-close="handleClose2"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form>
        <el-select v-model="userId" filterable placeholder="请选择">
          <el-option
            v-for="item in users"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          >
          </el-option>
        </el-select>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAllocate = false">取 消</el-button>
        <el-button type="primary" @click="commitAllocateUser()"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      title="大件预分配数量"
      :visible.sync="dialogAllocate2"
      :before-close="handleClose2"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form>
        <el-input
          placeholder="请输入预分配数量"
          v-model="dialogAllocateQty"
          type = number
          clearable>
        </el-input>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogAllocate2 = false">取 消</el-button>
        <el-button type="primary" @click="commitAllocateQty()"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <div class="publicSearch">
      <div class="searchBar" :style="{ height: isMoreSearch ? 'auto' : '' }">
        <el-button-group>
          <el-button
            @click="getWaveDetailData"
            size="mini"
            icon="el-icon-search"
            >查询</el-button
          >
          <el-button @click="clearSearchData" size="mini" icon="el-icon-refresh"
            >重置</el-button
          >
        </el-button-group>
        <div>
          <span>物料</span>
          <el-input
            v-model="searchData2.keyWords"
            size="mini"
            placeholder="名称/编码"
            clearable
          ></el-input>
        </div>
        <div>
          <span>发料属性</span>
          <el-input
            v-model="searchData2.feedCategory"
            size="mini"
            placeholder="请输入"
            clearable
          ></el-input>
        </div>
        <!-- <div>
          <span>红蓝字</span>
          <el-select
            v-model="searchData2.rob"
            size="mini"
            filterable
            placeholder="请选择"
            clearable
          >
            <el-option
              key="0"
              value="0"
              label="返还件"
            ></el-option>
            <el-option
              key="1"
              value="1"
              label="普通件"
            ></el-option>
          </el-select>
        </div> -->

        <div>
          <span>状态</span>
          <el-select
            v-model="searchData2.state"
            size="mini"
            filterable
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="state in states"
              :key="state.value"
              :value="state.value"
              :label="state.label"
            ></el-option>
          </el-select>
        </div>
      </div>
    </div>

    <div class="headerBtns"></div>

    <div class="tableBox organizationLeftTab" style="width: 20%">
      <el-table
        id="divContainer"
        ref="waveTable"
        highlight-current-row
        @current-change="handleSelChange"
        v-loading="loading.parent"
        :data="WaveMasters"
        style="width: 100%"
      >
        <el-table-column sortable prop="code" label="配料单">
          <template slot-scope="scope">
            <el-card class="box-card" style="margin-right: 25px">
              <div slot="header" class="clearfix">
                <span>{{ scope.row.code }}</span>

                <!-- <el-button  style="float: right; padding: 3px 0"  type="text" @click="showTransWaveModal">分配  </el-button> -->
                <!-- <el-button @click="deleteWaveConfirm(scope.row.waveId)" style="float: right; padding: 3px 0" type="text">删除</el-button> -->
              </div>

              <div v-if="scope.row.state != null">
                状态：
                <span style="color: #f56c6c" v-if="scope.row.state == 0"
                  >新建</span
                >
                <span style="color: #8b3a62" v-if="scope.row.state == 4"
                  >执行中</span
                >
                <span style="color: #67c23a" v-if="scope.row.state == 8"
                  >已完成</span
                >
              </div>
              <div>生成时间：{{ scope.row.createTime }}</div>
              <div>操作员：{{ scope.row.allotUserName }}</div>

              <div>
                订单总数：{{ scope.row.totalBillCount }}
                <!-- /{{
                  scope.row.soCountLimit
                }} -->
              </div>
              <div>
                sku总数：{{ scope.row.totalSkuCount }}
                <!-- /{{ scope.row.itemCount }} -->
              </div>
              
              <div margin-right="5px!import" v-if="scope.row.state == 0"> 
                <el-button
                size="small"
                class="rightFloat"
                type="warning"
                round
                @click="cancelWave(scope.row.code)"
                >
              取消
            </el-button> </div>
            </el-card>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="text-align: right"
        class="pagination-bottom"
        @current-change="handleCurrentChange"
        :current-page.sync="searchData.pageNum"
        :page-size="searchData.pageSize"
        @size-change="handleSizeChange"
        :page-sizes="[15, 30, 50, 100]"
        layout="sizes,total, prev, pager, next  "
        :total="searchData.total"
      >
      </el-pagination>
    </div>
    <div class="organizationMiddle">
      <!--  <i class="el-icon-d-arrow-right"></i> -->
    </div>
    <div class="tabs organizationRight" style="width: 70%">
      <el-tabs
        class="tabs organizationRight"
        style="width: 100%"
        type="border-card"
        tab-position="top"
        v-model="activeName"
      >
        <el-tab-pane label="明细信息" name="first">
          <div class="headerBtns">
            <el-button
              size="small"
              :disabled="mergeFlg"
              type="primary"
              round
              @click="allocateUser"
            >
              分配仓管员
            </el-button>

            <!-- <el-button
              size="small"
              type="info"
              round
              @click="allocateQty"
            >
              大件预分配
            </el-button>

            <el-button
              size="small"
              :disabled="virtualFlg"
              type="primary"
              round
              @click="virtualLog"
            >
              直发虚仓出库
            </el-button>

            <el-button
              size="small"
              :disabled="VMIFlg"
              type="primary"
              round
              @click="vmiDialog"
            >
              VMI入库
            </el-button>

            <el-button
              size="small"
              :disabled="virtualFlg"
              type="primary"
              round
              @click="xfCk"
            >
              先发配件出库
            </el-button> -->
            <el-button
              size="small"
              type="primary"
              round
              class="rightFloat"
              @click="syncCurrentData()"
            >
              同步拉取
            </el-button>

          </div>
          <div class="tableBox">
            <el-table
              highlight-current-row
              v-loading="loading.child"
              :expand-row-keys="expands"
              @expand-change="onChange"
              @selection-change="handleWaveDetailSelChange"
              :row-class-name="tableRowClassName"
              :data="WaveDetails"
              style="width: 100%"
            >
              <!-- <el-table-column fixed="left" type="index" width="50"> -->

              <!-- </el-table-column> -->
              <el-table-column type="selection" width="55"> </el-table-column>
              <!-- <el-table-column
                show-overflow-tooltip
                prop="stateView"
                label="状态"
                width="100"
              >
                <template slot-scope="scope">
                  <span v-if="scope.row.state == 0" style="color: #909399"
                    >待分配</span
                  >

                  <span v-if="scope.row.state == 4" style="color: #81ce65"
                    >执行中</span
                  >
                  <span v-if="scope.row.state == 8" style="color: #67c23a"
                    >已完成</span
                  >
                </template>
              </el-table-column> -->
              <el-table-column
                sortable
                show-overflow-tooltip
                prop="itemCode"
                label="物料编码"
                width="150"
              >
              </el-table-column>
              <el-table-column
                sortable
                show-overflow-tooltip
                prop="itemName"
                label="物料名称"
                width="150"
              >
              </el-table-column>
              <!-- <el-table-column
                sortable
                show-overflow-tooltip
                prop="feedCategory"
                label="发料属性"
                width="150"
              >
              </el-table-column> -->
              <el-table-column
                  sortable
                  show-overflow-tooltip
                  prop="rob"
                  label="红蓝字"
                  width="100"
              >
                <template slot-scope="scope">
            <span>{{ scope.row.rob?"普通件":"返还件"  }}</span
            >
                </template>
              </el-table-column>
              <!-- <el-table-column type="expand" label="展开" width="80">
                <template slot-scope="props">
                  <el-table
                    highlight-current-row
                    :data="expandList"
                    style="width: 80%; margin-left: 10%"
                  >
                    <el-table-column
                      show-overflow-tooltip
                      prop="areaCode"
                      label="库区编码"
                      width="250"
                    >
                    </el-table-column>
                    <el-table-column
                      show-overflow-tooltip
                      prop="areaName"
                      label="库区名称"
                      width="250"
                    >
                    </el-table-column>
                    <el-table-column
                      show-overflow-tooltip
                      prop="quantity"
                      label="数量"
                      width="250"
                    ></el-table-column>
                  </el-table>
                </template>
              </el-table-column> -->
              <el-table-column
                show-overflow-tooltip
                prop="orderQty"
                label="数量"
                width="100"
              >
              </el-table-column>
              <!-- <el-table-column
                show-overflow-tooltip
                prop="preAllottedQuantity"
                label="预分配数量"
                width="100"
              >
              </el-table-column> -->
              <el-table-column
                show-overflow-tooltip
                prop="allotQty"
                label="分配数量"
                width="100"
              >
              </el-table-column>
              <el-table-column
                show-overflow-tooltip
                prop="pickQty"
                label="拣货数量"
                width="100"
              >
              </el-table-column>
              <!-- <el-table-column
                show-overflow-tooltip
                prop="xfQuantity"
                label="先发配件数量"
                width="110"
              >
              </el-table-column>
              <el-table-column
                show-overflow-tooltip
                prop="invQty"
                label="可用库存"
                width="100"
              >
              </el-table-column> -->



              <!-- <el-table-column
                show-overflow-tooltip
                prop="packDescribe"
                label="单位"
                width="80"
              >
              </el-table-column> -->

              <el-table-column
                sortable
                show-overflow-tooltip
                prop="pickUserName"
                label="库管员"
                width="180"
              >
              </el-table-column>

              <!-- <el-table-column
                                fixed="right"
                                label="操作"
                                width="110">
                            <template slot-scope="scope">
                                <el-button @click="isDelete(scope.row.waveDetailId)" icon="iconfont icon-shanchu"
                                           type="danger" circle
                                           plain size="small"></el-button>
                            </template>
                        </el-table-column> -->
            </el-table>
          </div>
          <div>
            <!-- <el-button @click="$router.push({name: 'ChooseSo', params: {waveMasterId: WaveData.waveId}})">添加波次明细
                    </el-button>
                    <el-button @click="showTransWaveModal">转移至其它波次
                    </el-button> -->
          </div>
        </el-tab-pane>
      </el-tabs>

      <el-dialog
          title="产成品上架"
          :visible.sync="dialogNewVisible"
          :before-close="handleClose"
          width="1000px"
          style="margin-top: -10vh"
      >
        <div class="upperTacticBox">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group v-model="form.checkedCities" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="city in cities" :label="city" :key="city">{{city}}</el-checkbox>
          </el-checkbox-group>

          <el-form class="searchBar" :model="form"  ref="form">

            <el-form-item label="上架货区" prop="areaCode" :label-width="formLabelWidth">
              <el-select
                  v-model="form.areaCode"
                  filterable
                  placeholder="请选择货区"
                  size="small"
                  style="width: 70%"
                  @change="shoWCell"
              >
                <el-option
                    v-for="item in areas"
                    :key="item.areaCode"
                    :label="item.areaName"
                    :value="item.areaCode"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="上架货位" prop="cellCode" :label-width="formLabelWidth">
              <el-select
                  v-model="form.cellCode"
                  filterable
                  placeholder="请选择货位"
                  size="small"
                  style="width: 70%"
              >
                <el-option
                    v-for="item in cells"
                    :key="item.cellCode"
                    :label="item.cellName"
                    :value="item.cellCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div style="float: left; width: 100%"></div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button
              @click="
            dialogNewVisible = false;
          "
          >取 消</el-button>
          <el-button type="primary" @click="vim">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";

export default {
  name: "WaveMaster",
  data() {
    return {
      states: [
        {
          value: 0,
          label: "待分配",
          color: "#F56C6C",
        },
        {
          value: 1,
          label: "部分分配",
          color: "#8B3A62",
        },
        {
          value: 2,
          label: "完全分配",
          color: "#543044",
        },
        {
          value: 4,
          label: "已出库",
          color: "#543044",
        },
        {
          value: 3,
          label: "部分出库",
          color: "#543044",
        },
        {
          value: 8,
          label: "已完成",
          color: "#67C23A",
        },
      ],
      isIndeterminate: true,
      dialogNewVisible:false,
      form: {
        checkedCities: [],
        agreementNo: "", // 履约号
        billNo: "", //任务单号--只需要将这个传到后台
        dictValue: "", //入库类型
        wareName: "", //仓库
        uda3: "", //车间部门
        detailList: "", //明细数据,
        areaCode: "", //库区信息
        cellCode: "" //库位信息
      },
      wareId: PF.getLocal("wareId", "number"),
      users: [],
      userId: "",
      checkAll: false,
      isMoreSearch: false,
      activeName: "first",
      areas: [],
      searchData: {
        state: null,
        pageNum: 1,
        pageSize: 10,
        total: null,
        keyWords: "",
        wareId: PF.getLocal("wareId", "number"),
      },
      searchData2: {
        feedCategory: "", //发料属性
        state: null,

        pageNum: 1,
        pageSize: 10,
        total: null,
        keyWords: "",
        wareId: PF.getLocal("wareId", "number"),
      },
      childSearchData: {
        waveId: "",
      },
      pickTaskSearch: {
        pageNum: 1,
        pageSize: 10,
        total: null,
        waveId: "",
        wareId: PF.getLocal("wareId", "number"),
      },

      WaveMasters: [],
      WaveData: {},
      WaveDetails: [],
      pickTasks: [],

      formLabelWidth: "120px",

      asnUdfHs: [],
      organizations: [],
      suppliers: [],

      waveSelection: [],
      waveDetailSelection: [],
      newWaveSelection: [],
      waveMasterId: "",
      waveDetailIds: [],

      dialogTransVisible: false,
      pushUrl : '',
      waveScheduleState: 0,
      cities: [],
      cityOptions: [],
      editCronVisible: false,
      cronExpression: "",
      jobId: null,

      loading: {
        parent: false,
        child: false,
      },

      // 控制分配的页面
      dialogAllocate: false,
      dialogAllocate2: false,
      dialogAllocateQty: null,
      waveCode: '',

      expandList: [],
    };
  },
  computed: {
    ...mapState([]),
    //普通间,返还件,只能分配一种.不能同时分配两种

    mergeFlg() {
      let robArray = [];
      this.waveDetailSelection.forEach((item) => {
        robArray.push(item.rob);
      });
      return [...new Set(robArray)].length >= 2;
    },
    allocationFlg() {
      // if (this.waveDetailSelection.length == 1) {
      //   let obj = this.waveDetailSelection[0];
      //   console.log(obj)
      //   if (obj.state < 2 && obj.feedCategory == "GW9") {
      //     return false;
      //   }
      // }
      // return true;
    },
    VMIFlg () {
    },
    virtualFlg () {

      let robArray = [];
      this.waveDetailSelection.forEach((item) => {
        robArray.push(item.cellCode);
      });
       // console.log(robArray)
      robArray = [...new Set(robArray)]
      return false;
      // if (robArray.length >= 1 && robArray[0].cellCode != null) {
      //   return robArray[0].cellCode !== "ZF01-01-01";
      // } else {
      //   return true;
      // }

    }
  },
  methods: {
    vim() {
      let ids = []
      console.log(this.waveDetailSelection,"this.waveDetailSelection")
      this.waveDetailSelection.forEach((item) => {
        ids.push(item.waveDetailId);
      });
     let searchData = {
        ids: ids.join(","),
       oldCellCods : this.form.checkedCities.join(","),
       cellCode: this.form.cellCode //库位信息
      }
      IOT.getServerData(this.pushUrl, "get",
          searchData, ret => {
        this.loading.table = false;
        if (ret.code === 200) {
          alert("入库成功")
          this.vmiCellCode();
          this.dialogNewVisible = false;
        } else {
          IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
        }
      });
    },


    vmiDialog(){
      this.pushUrl = '/wave/vmi';
      this.dialogNewVisible = true;
      this.getAreaData();
      this.vmiCellCode(471713);
    },
    virtualLog() {
      this.pushUrl = '/wave/virtual'
      this.dialogNewVisible = true;
      this.getAreaData();
      this.vmiCellCode(null);
    },
    vmiCellCode(asnStockId) {
      let detailIds = [];
      let obj =  this.waveDetailSelection;
      obj.forEach(item=>{
        detailIds.push(item.waveDetailId)
      })

      IOT.getServerData(
          "/wave/findCode",
          "get",
          {
            ids: detailIds.join(","),
            asnStockId:asnStockId
          },
          ret => {
            if (ret.code === 200) {
              console.log(ret)
              this.cities = ret.rows
              this.cityOptions =ret.rows
            } else {
              IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
            }
          });
    },
    getCellData() {
      let searchData = {
        areaCode: this.form.areaCode,
        pageNum: 1,
        pageSize: 999
      };
      IOT.getServerData("/cell/infos/list", "get", searchData, ret => {
        this.loading.table = false;
        if (ret.code === 200) {
          this.cells = ret.rows;
          this.form.cellCode = ret.rows[0].cellCode
          console.log(ret.rows,"this.cellls")
          // console.log(ret.rows[0].cellCode)
        } else {
          IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
        }
      });
    },
    // 获取成品库区
    getAreaData() {
      IOT.getServerData(
          "/area/infos/list",
          "get",
          {
            wareId: PF.getLocal("wareId", "number"),
            pageSize: "999"
          },
          ret => {
            if (ret.code === 200) {
              let list = ret.rows;
              this.form.areaId = null;
              // 进行二次筛选--去掉半成品
              for (let i = 0; i < list.length; i++) {
                // 去掉半成品
                if (list[i].areaName.includes("半成品")) {
                  list.splice(i, 1);
                  i=0;
                }
              }
              console.log(PF.JSON(list));
              this.areas = list;
            } else {
              IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
            }
          }
      );
    },


      tableRowClassName({row, rowIndex}) {
        //虚仓
        if (row.cellCode === 'ZF01-01-01') {
          return 'warning-row';
        }
        return '';
      },


    getUserName(userId) {
      this.users.forEach((user) => {
        if (user.userId == userId) {
          return user.userName;
        }
      });
    },
    allotWave(waveMaster) {
      waveMaster.allotUserName = this.getUserName(waveMaster.allotUserId);
      IOT.getServerData("/wave/masters/update", "post", waveMaster, (ret) => {
        if (ret.code === 200) {
        } else {
          waveMaster.allotUserId = null;
          IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
        }
      });
    },
    getUsers() {
      IOT.getServerData(
        "/ware/infos/findUserByWareId",
        "get",
        { wareId: this.wareId },
        (ret) => {
          if (ret.code === 200) {
            this.users = ret.rows;
            console.log(JSON.stringify(this.users));
          } else {
            IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
          }
        }
      );
    },

    handleCheckAllChange(val) {
      this.form.checkedCities = val ? this.cityOptions : [];
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.cities.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
    },

    showEditCron() {
      this.editCronVisible = true;
    },
    handleCronClose() {
      this.editCronVisible = false;
    },
    handleSizeChange(val) {
      this.searchData.pageSize = val;
      this.getWaveMasterData();
      this.getWaveDetailData();
      // this.getPickTaskData();
    },
    handleCurrentChange(val) {
      this.searchData.pageNum = val;
      this.getWaveMasterData();
      this.getWaveDetailData();
      // this.getPickTaskData();
    },
    handleChildCurrentChange(val) {
      this.pageNum = val;
      // this.getPickTaskData();
    },
    handleChildSizeChange(val) {
      this.searchData.pageSize = val;
      // this.getPickTaskData();
    },
    handleSelChange(rowData) {
        this.waveCode = rowData.code
      this.childSearchData.waveId = rowData.waveId;
      this.pickTaskSearch.waveId = rowData.waveId;
      this.WaveData = JSON.parse(JSON.stringify(rowData));
      this.waveMasterId = rowData.waveId;

      this.getWaveDetailData();
      // this.getPickTaskData();
    },
    handleNewWaveSelChange() {},
    handleWaveDetailSelChange(val) {
      this.waveDetailSelection = val;
    },
    clearSearchData() {
      this.searchData2.keyWords = "";
      this.searchData2.state = null;
      this.searchData2.feedCategory = null;
      this.searchData2.rob = null;
    },
    getWaveMasterData() {
      this.loading.parent = true;
      IOT.getServerData("/wave/masters/list", "get", this.searchData, (ret) => {
        this.loading.parent = false;
        if (ret.code === 200) {
          this.WaveMasters = ret.rows;
          this.WaveData = ret.rows[0] || {};
          this.searchData.total = ret.total;
          this.searchData.pageNum = ret.pageNumber;
          if (ret.rows.length == 0) {
            this.loading.parent = false;
            return;
          }
          this.$refs.waveTable.setCurrentRow(ret.rows[0]);
          this.childSearchData.waveId = ret.rows[0].waveId;
          this.pickTaskSearch.waveId = ret.rows[0].waveId;
          this.getWaveDetailData();
          // this.getPickTaskData();
        } else {
          IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
        }
      });
    },
    getWaveDetailData() {
      this.loading.child = true;
      IOT.getServerData(
        "/wave/details/" + this.childSearchData.waveId,
        "get",
        this.searchData2,
        (ret) => {
          this.loading.child = false;
          console.log(JSON.stringify(ret));
          if (ret.code === 200) {
            this.WaveDetails = ret.rows;
          }
        }
      );
    },
    getPickTaskData() {
      this.loading.child = true;
      IOT.getServerData(
        "/pick/tasks/findByWaveMasterId",
        "get",
        this.pickTaskSearch,
        (ret) => {
          this.loading.child = false;
          if (ret.code === 200) {
            this.pickTasks = ret.rows;
            this.pickTaskSearch.total = ret.total;
            this.pickTaskSearch.pageNum = ret.pageNumber;
          }
        }
      );
    },

    onChange(item, expandedRows) {
      console.log("item:", item);
      console.log("expandedRows:", expandedRows);
      if (expandedRows.length) {
        this.expands = [];
        this.expands.push(item.acceptRecordCode);
        IOT.getServerData(
          "/inventorys/area/stock",
          "get",
          { itemCode: item.itemCode },
          (ret) => {
            console.log("查询订单物料返回：", ret);
            if (ret.code === 200) {
              this.expandList = ret.rows;
              console.log("---." + this.expandList);
            } else {
              IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
            }
          }
        );
      }
    },

    allocateUser() {
      //需要判断 是否勾选了波次明细
      if (this.waveDetailSelection.length == 0) {
        IOT.tips("请先选择明细！", "error");
        return;
      }
      for (var i = 0; i < this.waveDetailSelection.length; i++) {
        if (this.waveDetailSelection[i].state == 2) {
          IOT.tips("不能选择完全分配的明细！", "error");
          return;
        }
      }
      for (var i = 0; i < this.waveDetailSelection.length; i++) {
        if (this.waveDetailSelection[i].xfQuantity > 0) {
          IOT.tips("不能选择有先发配件的明细！", "error");
          return;
        }
      }
      this.dialogAllocate = true;
    },
    allocateQty() {
      this.dialogAllocate2 = true;
    },

    //分配提交
    commitAllocateUser() {
      //校验是否选择了仓管员
      // if (!this.userId) {
      //   IOT.tips("请先选择仓管员！", "error");
      //   return;
      // }
      var ids = "";
      for (var i = 0; i < this.waveDetailSelection.length; i++) {
        if (i == this.waveDetailSelection.length - 1) {
          ids += this.waveDetailSelection[i].waveDetailId;
        } else {
          ids += this.waveDetailSelection[i].waveDetailId + ",";
        }
      }
      // alert(this.userId);
      IOT.showOverlay("保存中，请稍等...");
      IOT.getServerData(
        "/wave/details/suggest",
        "post",
        { ids: ids, userId: this.userId },
        (ret) => {
          IOT.hideOverlay();
          if (ret.code === 200) {
            IOT.tips("保存成功！", "success", 1000, () => {
              // that.getWaveMasterData();
              this.userId = "";
              this.dialogAllocate = false;
              this.getWaveDetailData();
            });
          } else {
            IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
          }
        }
      );
    },

    virtual() {
      let detailIds = [];
      let obj =  this.waveDetailSelection;
      obj.forEach(item=>{
        console.log(item,"item")
        detailIds.push(item.waveDetailId)
      })

      IOT.getServerData(
          "/transfer/virtual",
          "get",
          {detailIds:detailIds.join(",")},
          (ret) => {
            IOT.hideOverlay();
            if (ret.code === 200) {
              IOT.tips("保存成功！", "success", 1000, () => {
                this.dialogAllocateQty = null;
                this.dialogAllocate2 = false;
                this.getWaveDetailData();
              });
            } else {
              IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
            }
          }
      );
    },
    commitAllocateQty() {
      //校验是否填写了数量
      if(!this.dialogAllocateQty || this.dialogAllocateQty == 0){
        IOT.tips("请先输入数量！", "error");
        return;
      }
      let obj = this.waveDetailSelection[0];
      if(this.dialogAllocateQty > (obj.quantity - obj.allottedQuantity)){
        IOT.tips("超出可预分配数量", "error");
        return;
      }
      // 不可超出先发配件数量
      if(this.dialogAllocateQty > obj.xfQuantity){
        IOT.tips("分配数量不能超过先发配件数量", "error");
        return;
      }
      obj.preAllottedQuantity = this.dialogAllocateQty;
      // alert(this.dialogAllocateQty);
      IOT.showOverlay("保存中，请稍等...");
      IOT.getServerData(
        "/wave/details/update",
        "post",
        obj,
        (ret) => {
          IOT.hideOverlay();
          if (ret.code === 200) {
            IOT.tips("保存成功！", "success", 1000, () => {
              this.dialogAllocateQty = null;
              this.dialogAllocate2 = false;
              this.getWaveDetailData();
            });
          } else {
            IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
          }
        }
      );
    },
    // 根据库区筛选库位
    shoWCell() {
      this.form.cellCode = '';
      this.getCellData();
      // 取消禁用
      this.isCell = false;
    },

    deleteWaveConfirm(id) {
      this.$confirm("确认删除？")
        .then((_) => {
          this.deleteWave(id);
        })
        .catch((_) => {});
    },
    deleteWave(id) {
      let that = this;
      IOT.showOverlay("删除中，请稍等...");
      IOT.getServerData("/wave/masters/delete", "get", { id: id }, (ret) => {
        IOT.hideOverlay();
        if (ret.code === 200) {
          IOT.tips("删除成功！", "success", 1000, () => {
            that.getWaveMasterData();
            that.getWaveDetailData();
          });
        } else {
          IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
        }
      });
    },

    isDelete(id) {
      this.$confirm("确认删除？")
        .then((_) => {
          this.deleteWaveDetail(id);
        })
        .catch((_) => {});
    },
    deleteWaveDetail(id) {
      let that = this;
      IOT.showOverlay("删除中，请稍等...");
      IOT.getServerData("/wave/details/delete", "get", { id: id }, (ret) => {
        IOT.hideOverlay();
        if (ret.code === 200) {
          IOT.tips("删除成功！", "success", 1000, () => {
            that.getWaveDetailData();
          });
        } else {
          IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
        }
      });
    },
    generateWaves() {
      let that = this;
      IOT.showOverlay("生成中，请稍等...");
      IOT.getServerData(
        "/wave/masters/generateWaves",
        "get",
        { wareId: PF.getLocal("wareId", "number") },
        (ret) => {
          IOT.hideOverlay();
          if (ret.code === 200) {
            IOT.tips("生成成功！", "success", 1000, () => {
              that.getWaveMasterData();
            });
          } else {
            IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
          }
        }
      );
    },

    showTransWaveModal() {
      if (this.waveDetailSelection.length <= 0) {
        IOT.tips("请至少选择一个波次明细！", "error", 1000, () => {
          IOT.hideOverlay();
        });
        return false;
      }
      let list = PF.JSON(this.waveDetailSelection);
      let waveDetailIds = [];
      for (let i = 0; i < list.length; i++) {
        waveDetailIds.push(list[i].waveDetailId);
      }
      this.waveDetailIds = waveDetailIds;

      this.dialogTransVisible = true;
    },
    handleClose() {
      this.dialogTransVisible = false;
    },
    handleClose2() {
      this.dialogAllocate = false;
      this.dialogAllocate2 = false;
    },
    transToWaveConfirm(waveId) {
      this.$confirm("确认转移至此波次？")
        .then((_) => {
          this.transToWave(waveId);
        })
        .catch((_) => {});
    },
    transToWave(waveId) {
      IOT.showOverlay("转移中，请稍等...");
      IOT.getServerData(
        "/wave/masters/transToWave",
        "post",
        {
          waveId: waveId,
          waveDetailIds: this.waveDetailIds,
        },
        (ret) => {
          IOT.hideOverlay();
          this.waveDetailSelection = [];
          this.waveDetailIds = [];
          if (ret.code === 200) {
            IOT.tips("保存成功！", "success");
            this.dialogTransVisible = false;
          } else {
            IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
          }
        }
      );
    },
    switchScheduledWaveTaskState() {
      let that = this;
      let state = this.waveScheduleState;
      IOT.getServerData(
        "/monitor/job/changeStatus",
        "post",
        { jobId: that.jobId, status: state },
        (ret) => {
          that.getWaveTaskState();
          if (ret.code === 200) {
          } else {
            IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
          }
        }
      );
    },
    cancelWave(waveCode) {
      IOT.showOverlay("转移中，请稍等...");
      IOT.getServerData(
        "/wave/masters/cancel",
        "get",
        {
          waveCode: waveCode,
        },
        (ret) => {
          if (ret.code === 200) {
            IOT.hideOverlay();
            IOT.tips("波次取消成功！", "success");
            this.getWaveMasterData();
          } else {
            IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
          }
        }
      );
    },

    getWaveTaskState() {
      IOT.getServerData(
        "/monitor/job/list",
        "get",
        {
          methodName: "waveParams",
          methodParams: PF.getLocal("wareId", "number"),
        },
        (ret) => {
          if (ret.code === 200) {
            this.waveScheduleState = ret.rows[0] ? ret.rows[0].status : 0;
            this.cronExpression = ret.rows[0] ? ret.rows[0].cronExpression : "";
            this.jobId = ret.rows[0] ? ret.rows[0].jobId : null;
          } else {
            IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
          }
        }
      );
    },

    syncCurrentData() {
      IOT.showOverlay("同步中，请稍等...");
      IOT.getServerData(
        "/wave/details/sync/data",
        "get",
        {
          waveCode: this.waveCode
        },
        (ret) => {
          if (ret.code === 200) {
            IOT.hideOverlay();
            this.getWaveMasterData();
          } else {
            IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
            IOT.hideOverlay();
          }
        }
      );
    },

    commitCronUpdate() {
      let that = this;
      IOT.showOverlay("保存中~~~");
      IOT.getServerData(
        "/monitor/job/updateCron",
        "post",
        { jobId: that.jobId, cronExpression: that.cronExpression },
        (ret) => {
          IOT.hideOverlay();
          if (ret.code === 200) {
            IOT.tips(ret.message || "保存成功！");
            that.getWaveTaskState();
            that.editCronVisible = false;
          } else {
            IOT.tips(ret.message || "server error!", "error");
          }
        }
      );
    },
    // 先发配件出库
    xfCk(){
      // 当前选中的数据--只能选中一个
      let obj = this.waveDetailSelection[0];
      //校验是否填写了数量
      if(obj.xfQuantity<1){
        IOT.tips("该物料不能先发配件出库", "error");
        return;
      }
      let ids=obj.waveDetailId;
      IOT.showOverlay("保存中，请稍等...");
      IOT.getServerData(
        "/wave/details/xfPjCk",
        "post",
        { ids: ids, userId: this.userId },
        (ret) => {
          IOT.hideOverlay();
          if (ret.code === 200) {
            IOT.tips("保存成功！", "success", 1000, () => {
              this.dialogAllocateQty = null;
              this.dialogAllocate2 = false;
              this.getWaveDetailData();
            });
          } else {
            IOT.tips(ret.message || "服务器请求失败，稍后再试！", "error");
          }
        }
      );
    }

  },
  created() {
    this.getUsers();
    this.getWaveMasterData();
    // PF.getSysParamUdfData("asnUdfHs", [], (data, udfs) => {
    //   this.asnUdfHs = udfs;
    // });
    // PF.getOrganizations((rows) => {
    //   this.organizations = rows;
    // });
    // PF.getSuppliers((rows) => {
    //   this.suppliers = rows;
    // });
    // this.getWaveTaskState();
  },
  mounted() {},
};
</script>

<style scoped lang="less">
#divContainer {
  //height: 900px;
  //overflow: auto;
}

#divContainer::-webkit-scrollbar {
  border-width: 1px;
}
.detailItemBox {
  display: inline-block;
  margin-top: 20px;
  width: 300px;
  span {
    flex: 1;
  }
}
.current-row {
  .el-button--text {
    color: white;
  }
  .el-card {
    background-color: #409eff;
    color: white;
  }
}

</style>

<style>
.el-table .warning-row {
  background: #fae5cb;
}


</style>
